package com.shop.shop_end.controller;
import cn.hutool.core.util.ObjectUtil;
import com.shop.shop_end.dto.LoginUser;
import com.shop.shop_end.dto.TopicVo;
import com.shop.shop_end.entity.*;
import com.shop.shop_end.exception.ServiceException;
import com.shop.shop_end.service.*;
import com.shop.shop_end.utils.DateUtils;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import com.shop.shop_end.variable.ErrorCodeEnum;
import com.shop.shop_end.vo.*;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

//定义为控制器
@Controller
@RequiredArgsConstructor
// 设置路径
//@RequestMapping(produces = "text/plain;charset=utf-8")
//@RequestMapping(produces = "application/json;charset=UTF-8")
public class PublicController extends BaseController{
    final Logger logger = LoggerFactory.getLogger(PublicController.class);

    private final AdminService adminService;

    private final GoodService goodService;

    private final CateService cateService;

    private final UserService userService;

    private final OrderService orderService;

    private final TopicService topicService;

    private final ComplainService complainService;

    //测试
    @RequestMapping("/")
    @ResponseBody
    public Result hello() {
        return ResultUtil.ok("success");
    }

    //公共

    /**
     * 设置session【因为每次重启后，session会被清除】
     * @return
     */
    @RequestMapping("/public/setSession")
    @ResponseBody
    public Result setSession(){
        Admin admin = (Admin) this.getRequest().getSession().getAttribute("admin");
        User user = (User) this.getRequest().getSession().getAttribute("user");
        logger.info("admin==>{}", admin);
        logger.info("user==>{}", user);
        if (admin == null && user == null){
            return ResultUtil.fail("token过期或其他异常，session无效");
        }else {
            return ResultUtil.ok();
        }
    }

    /**
     * 用户相关
     */
    //用户主页
    @RequestMapping("/user/index")
    public String userIndex() {
        //加载一些信息
        List<Cate> cateList = this.cateService.getAllCate();
        List<GoodVo> goodVoList = this.goodService.getAllGoods();
        List<CateVo> cateVoList = new ArrayList<>();
        this.getRequest().setAttribute("cateList", cateList);
        for (int i = 0; i < cateList.size(); i++) {
            CateVo cateVo = new CateVo();
            List<GoodVo> itemGoodList = new ArrayList<>();
            String cateName = cateList.get(i).getCateName();
            Long cateId = cateList.get(i).getCateId();
            cateVo.setCateId(cateId);
            cateVo.setCateName(cateName);
            cateVo.setMemo(cateList.get(i).getMemo());
            cateVo.setCreateTime(DateUtils.format(cateList.get(i).getCreateTime()));
            //查询此分类的商品
            logger.info("cateName==>{}", cateName);
            Integer num = 0;
            for (int j = 0; j < goodVoList.size(); j++) {
                if (goodVoList.get(j).getCateId() == cateId){
                    itemGoodList.add(goodVoList.get(j));
                    ++num;
                }
                if (num == 0){
                    break;
                }
            }
            cateVo.setGoodList(itemGoodList);
            cateVoList.add(cateVo);
        }
        logger.info("最终查询结果为==>{}", cateVoList);
        this.getRequest().setAttribute("frontList", cateVoList);
        return "/user/index";
    }

    //用户全部商品页面
    @RequestMapping("/user/getAllGoods")
    public String userGetAllGoods() {
        //加载商品信息
        List<Cate> cateList = this.cateService.getAllCate();
        List<GoodVo> goodVoList = this.goodService.getAllGoods();
        logger.info("最终查询结果为cateList==>{}, goodList==>{}", cateList, goodVoList);
        this.getRequest().setAttribute("cateList", cateList);
        this.getRequest().setAttribute("goodList", goodVoList);
        return "/user/index";
    }

    //用户登录
    @RequestMapping("/user/loginPage")
    public String userLogin() {
        return "/user/login";
    }

    //用户注册
    @RequestMapping("/user/registerPage")
    public String userRegister() {
        return "/user/register";
    }

    @RequestMapping("/user/userCenter")
    public String userCenter() {
        return "/user/userCenter";
    }

    @RequestMapping("/user/userInfo")
    public String userInfo() {
        return "/user/userInfo";
    }

    // 普通用户退出登录
    @RequestMapping("/user/exit")
    public String userExit() {
        this.getRequest().getSession().removeAttribute("user");
        return "redirect:/user/loginPage";
    }

    /**
     * 管理员相关
     */
    //管理员首页
    @RequestMapping("/admin/main")
    public String adminIndex() {
        return "/admin/main";
    }

    //管理员登录页面
    @RequestMapping("/admin/loginPage")
    public String adminLogin() {
        return "/admin/login";
    }

    //管理员注册
    @RequestMapping("/admin/registerPage")
    public String adminRegister() {
        return "/admin/register";
    }

    // 管理员准备修改密码
    @RequestMapping("/admin/prePwd")
    public String prePwd() {
        return "/admin/editPwd";
    }
    //展示所有用户
    @RequestMapping("/admin/getAllUsers")
    public String getAllUsers(){
        return "/admin/listUsers";
    }

    //管理员进入修改个人信息页面
    @RequestMapping("/admin/getAdminById")
    public String getAdminById(){
        Long adminId = Long.valueOf(this.getRequest().getParameter("adminId"));
        logger.info("adminId为 {}", adminId);
        if (ObjectUtil.isNull(adminId)){
            throw new ServiceException(ErrorCodeEnum.PARAMS_ERROR, "adminId错误，adminId==>"+ adminId);
        }
        Admin admin = adminService.getAdminById(adminId);
        this.getRequest().setAttribute("admin", admin);
        return "/admin/editAdmin";
    }

    // 管理员退出登录
    @RequestMapping("/admin/exit")
    public String exit() {
        this.getRequest().getSession().removeAttribute("admin");
        return "redirect:/admin/loginPage";
    }

    // 准备添加数据
    @RequestMapping("/admin/createAdmin")
    public String createAdmin() {
        return "/admin/addAdmin";
    }


    //good相关
    @RequestMapping("/good/getAllGoods")
    public String getAllGoods(){
        List<GoodVo> goodList = goodService.getAllGoods();
        this.getRequest().setAttribute("goodList", goodList);
        logger.info("goodList==>{}", goodList);
        return "/admin/listGoods";
    }

    // 按主键查询数据
    @RequestMapping("/good/getGoodsById")
    public String getGoodsById(Long id) {
        GoodVo goodVo = this.goodService.getGoodsById(id);
        this.getRequest().setAttribute("good", goodVo);
        List<Cate> cateList = this.cateService.getAllCate();
        this.getRequest().setAttribute("cateList", cateList);
        return "/admin/editGood";
    }

    // 通过主键删除数据
    @RequestMapping("/good/deleteGood/{id}")
    public String deleteGoods(@PathVariable("id") Long id) {
        this.goodService.deleteGoodById(id);
        return "redirect:/admin/getAllGoods";
    }

    // 准备添加数据
    @RequestMapping("/good/createGood")
    public String createGoods() {
        List<Cate> cateList = this.cateService.getAllCate();
        this.getRequest().setAttribute("cateList", cateList);
        return "/admin/addGood";
    }


    //cate类型相关
    // 显示全部数据
    @RequestMapping("/cate/getAllCates")
    public String getAllCate() {
        List<Cate> cateList = this.cateService.getAllCate();
        this.getRequest().getSession().setAttribute("cateList", cateList);
        logger.info("cateList=>{}", cateList);
//        PageHelper.getPage(cateList, "cate", null, null, 10, number, this.getRequest(), null);
        return "/admin/listCates";
    }

    // 准备添加数据
    @RequestMapping("/cate/createCate")
    public String createCate() {
        return "/admin/addCate";
    }

    // 按主键查询数据
    @RequestMapping("/cate/getCateById/{id}")
    public String getCateById(@PathVariable("id") Long id) {
        Cate cate = this.cateService.getCateById(id);
        this.getRequest().setAttribute("cate", cate);
        logger.info("cate==>{}", cate);
        return "/admin/editCate";
    }

    //订单order相关

    // 显示全部数据
    @RequestMapping("/order/getAllOrders")
    public String getAllOrder() {
        this.orderService.getAllOrder();
        return "/admin/listOrders";
    }

    /**
     * 按主键查询数据
     * @param id
     * @return
     */
    @RequestMapping("getOrderById")
    public Order getOrderById(Long id) {
        return orderService.getOrderById(id);
    }

    //用户user相关
    /**
     * 管理员获取所有用户
     * @return
     */
    @RequestMapping("/user/getAllUsers")
    public String getAllUser(){
        List<UserVo> userList = userService.getAllUserList();
        logger.info("userList==>{}", userList);
        this.getRequest().getSession().setAttribute("userList", userList);
        return "/admin/listUsers";
    }

    //topic相关
    // 准备添加数据
    @RequestMapping("/topic/createTopic")
    public String createTopic() {
        List<UserVo> usersList = this.userService.getAllUserList();
        this.getRequest().setAttribute("userList", usersList);
        List<OrderVo> ordersList = this.orderService.getAllOrder();
        this.getRequest().setAttribute("orderList", ordersList);
        List<GoodVo> goodsList = this.goodService.getAllGoods();
        this.getRequest().setAttribute("goodList", goodsList);
        return "/admin/addTopic";
    }

    // 显示全部数据
    @RequestMapping("/topic/getAllTopics")
    public String getAllTopic() {
        List<TopicVo> topicList = this.topicService.getAllTopic();
        logger.info("topicList==>{}", topicList);
        this.getRequest().setAttribute("topicList", topicList);
        return "/admin/listTopics";
    }

    // 按主键查询数据
    @RequestMapping("/topic/getTopicById")
    public String getTopicById(Long id) {
        TopicVo topicVo = this.topicService.getTopicById(id);
        this.getRequest().setAttribute("topic", topicVo);
        List<UserVo> usersList = this.userService.getAllUserList();
        this.getRequest().setAttribute("userList", usersList);
        List<OrderVo> ordersList = this.orderService.getAllOrder();
        this.getRequest().setAttribute("orderList", ordersList);
        List<GoodVo> goodsList = this.goodService.getAllGoods();
        this.getRequest().setAttribute("goodList", goodsList);
        return "/admin/editTopic";
    }


    //complain相关
    // 准备添加数据
    @RequestMapping("/complain/createComplain")
    public String createComplain() {
        List<UserVo> usersList = this.userService.getAllUserList();
        this.getRequest().setAttribute("usersList", usersList);
        return "/user/addComplain";
    }

    // 显示全部数据
    @RequestMapping("/complain/getAllComplains")
    public String getAllComplain() {
        List<ComplainVo> complainVoList = this.complainService.getAllComplain();
        this.getRequest().setAttribute("complainList", complainVoList);
        logger.info("complainVoList==>{}", complainVoList);
        return "/admin/listComplains";
    }


    // 按主键查询数据
    @RequestMapping("/complain/getComplainById")
    public String getComplainById(Long id) {
        ComplainVo complainVo = this.complainService.getComplainById(id);
        this.getRequest().setAttribute("complain", complainVo);
        List<UserVo> usersList = this.userService.getAllUserList();
        this.getRequest().setAttribute("userList", usersList);
        return "/admin/editComplain";
    }
}
